package com.hanxiang.hankol.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;

import androidx.annotation.NonNull;

import com.baselibrary.BuildConfig;
import com.baselibrary.adapter.CommonDynamicAdapter;
import com.baselibrary.utils.Config;
import com.baselibrary.utils.ContextUtils;
import com.baselibrary.utils.ImageUtil;
import com.baselibrary.utils.ThreadPoolUtils;
import com.baselibrary.utils.ToastUtils;
import com.baselibrary.utils.WxUtils;
import com.okhttp.callbacks.Callback;
import com.okhttp.utils.OkHttpUtils;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;


/**
 * Created by liang on 2017/2/28.
 */
public class WXManager {

    private static final String TAG = "WXManager";

    private static final String SP_WECHAT_INFO = "third_wechat_info";
    private static final String SP_WECHAT_OPENID = "third_wechat_openid";
    private static final String SP_WECHAT_AVATAR = "third_wechat_avatar";
    private static final String SP_WECHAT_TOKEN = "third_wechat_token";
    private static final String SP_WECHAT_CODE = "third_wechat_code";
    private static final String SP_WECHAT_NICKNAME = "third_wechat_nickname";


    public static final String URL_GET_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    public static final String URL_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";


    public static void startAuth(Context cxt) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(cxt, Config.WECHAT_APP_ID, false);
        iwxapi.registerApp(Config.WECHAT_APP_ID);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        iwxapi.sendReq(req);
    }

    public static void setWxLoginListener(WXEntryActivity.OnWxLoginCallBack onWxLoginCallBack) {
        WXEntryActivity.setWxLoginCallBack(onWxLoginCallBack);
    }

    public static void fetchToken(Callback call) {
        String code = getCode();
        String url = String.format(URL_GET_TOKEN, Config.WECHAT_APP_ID, Config.WECHAT_APP_SECRET, code);
        OkHttpUtils.getInstance().get().url(url).build().execute(call);
    }

    public static void fetchWxUserInfo(String token, String openid, Callback call) {
        String code = getCode();
        String url = String.format(URL_GET_USER_INFO, token, openid);
        OkHttpUtils.getInstance().get().url(url).build().execute(call);
    }

    public static void setCode(String code) {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        sp.edit().putString(SP_WECHAT_CODE, code).apply();
    }

    public static String getCode() {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        return sp.getString(SP_WECHAT_CODE, "");
    }

    public static void setNickname(String nickname) {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        sp.edit().putString(SP_WECHAT_NICKNAME, nickname).apply();
    }

    public static String getNickname() {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        return sp.getString(SP_WECHAT_NICKNAME, "");
    }

    public static void setToken(String token) {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        sp.edit().putString(SP_WECHAT_TOKEN, token).apply();
    }

    public static String getToken() {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        return sp.getString(SP_WECHAT_TOKEN, "");
    }

    public static void setOpenid(String openid) {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        sp.edit().putString(SP_WECHAT_OPENID, openid).apply();
    }

    public static String getOpenid() {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        return sp.getString(SP_WECHAT_OPENID, "");
    }

    public static void setAvatar(String avatar) {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        sp.edit().putString(SP_WECHAT_AVATAR, avatar).apply();
    }

    public static String getAvatar() {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        return sp.getString(SP_WECHAT_AVATAR, "");
    }

    public static void reset() {
        SharedPreferences sp = ContextUtils.getCurApplication().getSharedPreferences(SP_WECHAT_INFO,
                Activity.MODE_PRIVATE);
        sp.edit().clear().apply();
    }

    /**
     * @return true 安装 false 未安装
     */
    public static boolean isInstallWx(Context activity) {
        final PackageManager packageManager = activity.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isInstallQQ(Context activity) {
        final PackageManager packageManager = activity.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 微信图片分享
     *
     * @param shareType {@link SendMessageToWX.Req#WXSceneSession} 分享给微信好友
     *                  {@link SendMessageToWX.Req#WXSceneTimeline} 分享给朋友圈
     *                  {@link SendMessageToWX.Req#WXSceneFavorite} 收藏
     */
    public static void shareToWXImage(Context context, int shareType, @NonNull Bitmap bitmap) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, Config.WECHAT_APP_ID, false);
        iwxapi.registerApp(Config.WECHAT_APP_ID);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = new WXImageObject(bitmap);


        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = shareType;
        iwxapi.sendReq(req);
    }

    /**
     * APP分享微信小程序
     *
     * @param exeId 小程序ID
     * @param path  小程序路径
     */
    public static void shareToWxExe(Context context, String exeId, String path, String title, String desc, String url, String coverUrl) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, Config.WECHAT_APP_ID, false);
        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = url; // 兼容低版本的网页链接
        // 正式版:0，测试版:1，体验版:2
        miniProgramObj.miniprogramType = BuildConfig.DEBUG ? WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW : WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        miniProgramObj.userName = exeId; // 小程序原始id
        //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        miniProgramObj.path = path;
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = title; // 小程序消息title
        msg.description = desc; // 小程序消息desc
//        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = ImageUtil.getBitmap(coverUrl);
                if (null == bitmap) {
                    ToastUtils.showShort(context, "分享失败");
                    return;
                }
                msg.thumbData=WxUtils.getHtmlByteArray(coverUrl);// 小程序消息封面图片，小于128k
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = desc;//buildTransaction("miniProgram")
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession; // 目前只支持会话
                iwxapi.sendReq(req);
            }
        });
    }

    /**
     * 跳转微信小程序
     *
     * @author: merbng
     * @time: 2021/12/2 10:23
     * @description:
     */
    public static void jumpToWxExe(Context context, String exeId, String path) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, Config.WECHAT_APP_ID, false);
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = exeId; // 填小程序原始id
        req.path = path;                  //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        req.miniprogramType = BuildConfig.DEBUG ? WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW : WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        iwxapi.sendReq(req);
    }
}
